package com.lyl.auth;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.lyl.db.model.Role;
import com.lyl.db.repository.UsersRepository;

@Service
public class CustomUserDetailsService implements UserDetailsService {
	@Autowired
	private UsersRepository usersRepository;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		com.lyl.db.model.User sysUser = new com.lyl.db.model.User();
		sysUser.setLoginName(username);
		Example<com.lyl.db.model.User> example = Example.of(sysUser);

		Optional<com.lyl.db.model.User> optional = usersRepository.findOne(example);
		if (optional.isPresent()) {
			sysUser = optional.get();
		}
		Role role = sysUser.getRole();
		List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(role.getName());
		
		return new User(sysUser.getLoginName(), sysUser.getLoginPw(), authorityList);
	}

}
